import os

from pyftpdlib.authorizers import DummyAuthorizer
from pyftpdlib.handlers import FTPHandler
from pyftpdlib.servers import FTPServer
from pyftpdlib.log import LogFormatter
import logging

def MyFTPServer(username, password, port, directory):
    
    '''
    启动一个ftp的server进程
    :param username: 用户名
    :param password: 用户的密码
    :param port: 端口号
    :param directory: 用户的家目录,也就是ftp的数据目录
    '''
    
    authorizer = DummyAuthorizer()
    authorizer.add_user(username, password, directory, perm='elradfmwMT')
    authorizer.add_anonymous(os.getcwd())

    # Instantiate FTP handler class
    handler = FTPHandler
    handler.authorizer = authorizer

    # Define a customized banner (string returned when client connects)
    handler.banner = "pyftpdlib based ftpd ready."

    # Specify a masquerade address and the range of ports to use for
    # passive connections.  Decomment in case you're behind a NAT.
    #handler.masquerade_address = '151.25.42.11'
    handler.passive_ports = range(1025, 65535)

    # Instantiate FTP server class and listen on 0.0.0.0:2121
    address = ('', port)
    server = FTPServer(address, handler)

    # set a limit for connections
    server.max_cons = 256
    server.max_cons_per_ip = 5

    # start ftp server
    server.serve_forever()

if __name__ == '__main__':
    username = "rechie"
    password = "Linux1024!"
    port = "2121"
    directory = "/home/rechie/"
    logger = logging.getLogger()
    logger.setLevel(logging.INFO)
    log_file = logging.FileHandler(filename="ftp.log", encoding="utf-8")
    log_file.setFormatter(LogFormatter())
    logger.addHandler(log_file)
    MyFTPServer(username, password, port, directory)
    